package com.zhentao.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Date 2024/4/2 14:33
 * @Author xdm
 **/
//@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("执行到了TokenGlobalFilter");
        //获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        System.out.println("path:" + path);
        System.out.println(request.getQueryParams());
        System.out.println(request.getMethod());

        //获取token  header
        String token = request.getHeaders().getFirst("token");
        if (token != null && token.equals("123456")) {
            //放行
            return chain.filter(exchange);
        } else {
            //返回401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }


    }

    //排序 数字越小 优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
